import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { QueryDeepPartialEntity } from 'typeorm/query-builder/QueryPartialEntity';
import { ObjectLiteral } from 'typeorm/common/ObjectLiteral';
import { Record } from './entities/record.entity';
import { CreateRecordDto } from './dto/create-record.dto';
import { PageQuery } from '../../../util/entity/page.entity';
import { buildQuery } from '../../../util/common-fn';
import { UpdateRecordDto } from './dto/update-record.dto';
import { UserService } from '../../admin/user/user.service';
import { RoleEnum } from '../../../util/enum/role.enum';

@Injectable()
export class RecordService {
  constructor(
    @InjectRepository(Record)
    private recordRepository: Repository<Record>,
    private userService: UserService,
  ) {}
  /**
   * 插入记录
   */
  async insertValues<Entity extends ObjectLiteral>(
    values: QueryDeepPartialEntity<Entity> | QueryDeepPartialEntity<Entity>[],
  ) {
    await this.recordRepository
      .createQueryBuilder()
      .insert()
      .into(Record)
      .values(values)
      .execute();
  }
  create(createRecordDto: CreateRecordDto) {
    return this.recordRepository.save(createRecordDto);
  }

  async findAll(pageQuery: PageQuery<Record>, userId: number) {
    const isRootOrAdmin = await this.userService.hasOneOfRoles(userId, [
      RoleEnum.Root,
      RoleEnum.Admin,
    ]);
    let andWhere = {};
    if (!isRootOrAdmin) {
      andWhere = { user: { id: userId } };
    }
    const query = buildQuery(pageQuery, andWhere);
    return this.recordRepository.findAndCount(query);
  }

  findOne(id: number) {
    return this.recordRepository.findOneByOrFail({ id });
  }

  update(id: number, updateRecordDto: UpdateRecordDto) {
    return this.recordRepository.update({ id }, updateRecordDto);
  }

  remove(id: number) {
    return this.recordRepository.softDelete({ id });
  }
}
